'''
Created on 2018年9月11日

@author: lijie
'''
import os
import sys
import time
import unittest

import requests

from utilites.common import Common
from utilites.database_helper import MysqlHelper
from utilites.rmhelper import RunManageHelper


curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 

rm=RunManageHelper()
cm=Common()
isPass=True           #本轮次脚本运行结果标志
script_path=curPath
msg=rm.get_pub_msg()   #启动任务监听，接收需要测试的round名称
rid=str(msg['data'],'utf-8')
last_case=rm.get_last_case(rid)
i=1      #开始运行标志
n=3      #rerun次数
while True:
    task=rm.get_task_case_name(rid)        #在该round的任务队列中获取需要执行的脚本名称
    if task==None:
        print("任务列表为空!!")      #如果队列为空，则本次测试任务结束
        if isPass==True:
            rt='passed'
        else:
            rt='failed'
        etime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
        sql="update round set status=2,result='"+rt+"',etime='"+etime+"' where id="+rid
        MysqlHelper('ev1','rm').exc(sql)
        break
    #初始化测试轮次运行
    if i==1:
        stime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
        sql="update round set status=1,stime='"+stime+"' where id="+rid
        MysqlHelper('ev1','rm').exc(sql)
        i-=1
    
    task=str(task[1],'utf-8')
    rm.init_task_status(rid, task)              #获取到任务并在数据库中初始化该任务，表明该任务被客户端接收
    log_name=task.split('.')[0]
    log_dir = BASE_DIR + '/logs/'+time.strftime("%Y%m%d_%H%M%S",time.localtime(time.time()))+'_'+log_name+'.log'    #创建日志文件
    Common.logger=cm.get_logger(log_dir)                   #日志对象赋值给类变量logger
    cm.logger_info("init for round:"+rid+", task name:"+task)
      
    suite=unittest.TestSuite()
    test = unittest.defaultTestLoader.discover(start_dir=script_path,pattern=task)
    suite.addTest(test)

    runner = unittest.TextTestRunner(verbosity=2)
    result=runner.run(suite)
    reason=''
    for name,reason in result.failures:
        cm.logger_info(reason) 
        if len(reason)>0:
            isPass=False      
    rm.set_run_result(rid,task, reason)

    Common.logger=None
    # 如果执行完队列最后一个脚本，就向rm服务器发送自动重跑请求
    if task==str(last_case,'utf-8'):
        if n!=0:
            requests.get(rm.RMURL+'/round/autoRerun?rid='+rid)
            n-=1
                   
if __name__=='__main__': 
    pass

